//
//  SGGameViewController.m
//  EatNumber
//
//  Created by zg.shao on 14/12/20.
//  Copyright (c) 2014年 kuwo.cn. All rights reserved.
//

#import "SGGameViewController.h"
#import "GameAlgorithm.h"
#import "SGEatNumber.h"
#import "SGGameFinishedView.h"
#import "UIView+Sizes.h"
#import "CommonDef.h"
#import "SGAppDelegate.h"
#import "Appirater.h"

#define nSpaceWidth   7
#define nLeftSpace    10
#define nItemWidth    ((SCREEN_WIDTH - nLeftSpace*2 - nSpaceWidth * 4) / 5.0)

@interface SGGameViewController () <SGEatNumberDelegate, SGGameFinishedViewDelegate, UITextViewDelegate> {
    NSMutableArray *_cellBtnArray;
    UIView  *_theView;
    UILabel *_tipLabel;
    UILabel *_selectedLabel;
    UILabel *_highLightedLabel;
    CGPoint _differencePoint;       //手指与移动块的位置差
    
    UILabel *_readMeTextView;  // 新手教学文字提示
    
    SGGameFinishedView *_gameFinishedView;
    UILabel *_titleLabel;
    
    UIImageView *_handImageView;
    UIView *_lineView;
    BOOL _animationStopped; // 动画被中断了
}

@end

@implementation SGGameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = COLOR_WITH_RGB(0x617074);
    self.view.backgroundColor = COLOR_WITH_RGB(0xc3b7a9);
    
    _cellBtnArray = [[NSMutableArray alloc] initWithCapacity:GAME_CELL_MAX];
    
    [self initControllerButton];
    
    CGRect rect = CGRectMake(0, _titleLabel.bottom + 58, SCREEN_WIDTH, SCREEN_WIDTH);
    [self initSubViewWithFrame:rect];

    [[SGEatNumber defaultEatNumber] setDelegate:self];
    
    [self initTeachLevel];
    
    [self updateGameCellValue];
    
    [_titleLabel setText:[NSString stringWithFormat:@"LEVEL %d", (int)[[SGEatNumber defaultEatNumber] getCurLevel]]];
}

- (void)dealloc {
    [_selectedLabel removeObserver:self forKeyPath:@"text"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initSubViewWithFrame:(CGRect)frame {
    _theView = [[UIView alloc] initWithFrame:frame];
    _theView.height = GAME_ROW_MAX * nItemWidth + (GAME_ROW_MAX - 1) * nSpaceWidth;
    
    for (int row = 0; row < GAME_ROW_MAX; row ++) {
        for (int col = 0; col < GAME_COL_MAX; col ++) {
            CGRect rect = CGRectMake(col * (nItemWidth + nSpaceWidth) + nLeftSpace, row * (nItemWidth + nSpaceWidth)+ nLeftSpace, nItemWidth, nItemWidth);
            UILabel *btnItem = [[UILabel alloc] init];
            [btnItem setFrame:rect];
            [btnItem setFont:[UIFont fontWithName:@"AvenirNextCondensed-Heavy" size:28]];
            [btnItem setTextColor:[UIColor whiteColor]];
            [btnItem setTextAlignment:NSTextAlignmentCenter];
            [_cellBtnArray addObject:btnItem];
            
            [_theView addSubview:btnItem];
        }
    }
    
    // 选中的浮框
    _selectedLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, nItemWidth, nItemWidth)];
    [_selectedLabel setBackgroundColor:[UIColor blueColor]];
    [_selectedLabel setFont:[UIFont fontWithName:@"AvenirNextCondensed-Heavy" size:28]];
    [_selectedLabel setTextColor:[UIColor whiteColor]];
    [_selectedLabel setTextAlignment:NSTextAlignmentCenter];
    [_selectedLabel setHidden:YES];
    [_theView addSubview:_selectedLabel];
    
    // 提示浮窗
    _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(nItemWidth/4, -nItemWidth/2 - 5, nItemWidth/2, nItemWidth/2)];
    [_tipLabel setBackgroundColor:[UIColor darkGrayColor]];
    [_tipLabel setFont:[UIFont fontWithName:@"AvenirNextCondensed-Heavy" size:23]];
    [_tipLabel setTextColor:[UIColor whiteColor]];
    [_tipLabel.layer setCornerRadius:nItemWidth/4];
    [_tipLabel.layer setMasksToBounds:YES];
    [_tipLabel setTextAlignment:NSTextAlignmentCenter];
    [_tipLabel setAlpha:0.7];
    [_selectedLabel addSubview:_tipLabel];
    [_selectedLabel addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    
    // 进入区域的边框
    _highLightedLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, nItemWidth, nItemWidth)];
    [_highLightedLabel setBackgroundColor:[UIColor clearColor]];
    [_highLightedLabel setHidden:YES];
    [_highLightedLabel.layer setBorderColor:[UIColor whiteColor].CGColor];
    [_highLightedLabel.layer setBorderWidth:2.];
    [_theView addSubview:_highLightedLabel];
    
    if (!IS_IPHONE_4_OR_LESS) {
        [_theView setCenter:self.view.center];
    }
    
    if (IS_IPHONE_6P || IS_IPHONE_6 || IS_IPHONE_5) {
        _theView.top += 30;
    }
    
    _readMeTextView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH - 20, nItemWidth)];
    [_readMeTextView setTextAlignment:NSTextAlignmentCenter];
    _readMeTextView.numberOfLines = 0;
    [_readMeTextView setTextColor:[UIColor whiteColor]];
    [_readMeTextView setBackgroundColor:[UIColor clearColor]];
    [_readMeTextView setTextColor:[UIColor whiteColor]];
    [_readMeTextView setFont:[UIFont fontWithName:@"AvenirNextCondensed-Heavy" size:23]];
    _readMeTextView.shadowColor = COLOR_WITH_RGB(0x484848);
    _readMeTextView.shadowOffset = CGSizeMake(1, 1);
    [_theView addSubview:_readMeTextView];
    
    if (IS_IPHONE_6P) {
        _readMeTextView.top += 20;
    }
    
    [self.view addSubview:_theView];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    _tipLabel.text = [change objectForKey:@"new"];
    [_selectedLabel setBackgroundColor:[[SGEatNumber defaultEatNumber] getNumberColor:[[change objectForKey:@"new"] integerValue]]];
    [_tipLabel setBackgroundColor:_selectedLabel.backgroundColor];
}

- (void)initControllerButton {
    int buttonHeight = 38;
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, SCREEN_WIDTH-20, 20)];
    [_titleLabel setTextColor:[UIColor whiteColor]];
    [_titleLabel setTextAlignment:NSTextAlignmentCenter];
    [_titleLabel setFont:[UIFont systemFontOfSize:21]];
    [self.view addSubview:_titleLabel];
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, _titleLabel.bottom+10, (SCREEN_WIDTH/2-20), buttonHeight)];
    [backButton setImage:[UIImage imageNamed:@"btn_level"] forState:UIControlStateNormal];
    [backButton addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    UIButton *restartButton = [[UIButton alloc] initWithFrame:CGRectMake(backButton.right+10, backButton.top, backButton.width, buttonHeight)];
    [restartButton setImage:[UIImage imageNamed:@"btn_restart"] forState:UIControlStateNormal];
    [restartButton addTarget:self action:@selector(restartGame) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:restartButton];
    
    if (IS_IPHONE_6P) {
        _tipLabel.top += 30;
        backButton.top += 30;
        restartButton.top += 30;
    }
}

- (void)updateGameCellValue {
    static const NSInteger nWallImageViewTag = 24678;
    NSInteger *gameCells = [[SGEatNumber defaultEatNumber] gameCells];
    for (NSInteger i = 0; i < GAME_CELL_MAX; i ++) {
        UILabel *btn = [_cellBtnArray objectAtIndex:i];
        [btn setText:@""];
        UIColor *cellColor = [[SGEatNumber defaultEatNumber] getNumberColor:gameCells[i]];
        [btn setBackgroundColor:cellColor];
        UIView *oldImageView = [btn viewWithTag:nWallImageViewTag];
        if (oldImageView) {
            [oldImageView removeFromSuperview];
        }
        
        if (gameCells[i] == GameCellValue_Blank) {
            continue;
        } else if (gameCells[i] == GameCellValue_Wall) {
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, btn.size.width, btn.size.height)];
            [imgView setImage:[UIImage imageNamed:@"chain_cell"]];
            imgView.tag = nWallImageViewTag;
            [btn addSubview:imgView];
            btn.tag = -1;
        } else {
            NSString *title = [NSString stringWithFormat:@"%ld", (long)gameCells[i]];
            [btn setText:title];
        }
        
        btn.transform = CGAffineTransformMakeScale(0.1, 0.1);
        [UIView animateWithDuration:0.5 animations:^{
            btn.transform = CGAffineTransformMakeScale(1, 1);
        }];
    }
    
    NSString *tipString = [[SGEatNumber defaultEatNumber] tipString];
    if ([tipString length] > 0) {
        _readMeTextView.hidden = NO;
        [_readMeTextView setText:tipString];
        CGSize infoLabelSize = [tipString boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 20, nItemWidth * 2 + nSpaceWidth)
                                                           options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : _readMeTextView.font} context:NULL].size;
        [_readMeTextView setHeight:infoLabelSize.height];
    } else {
        [_readMeTextView setText:@""];
        _readMeTextView.hidden = YES;
    }
    
    NSInteger curLevelIndex = [[SGEatNumber defaultEatNumber] getCurLevel];
    [self teachUserWithLevel:curLevelIndex];
}

- (void)initTeachLevel {
    _handImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"s_hand"]];
    _handImageView.hidden = YES;
    [_theView addSubview:_handImageView];
    
    _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 6, 6)];
    _lineView.layer.cornerRadius = 3;
    _lineView.layer.masksToBounds = YES;
    _lineView.hidden = YES;
    [_lineView setBackgroundColor:[UIColor whiteColor]];
    _lineView.alpha = 0.6;
    [_theView addSubview:_lineView];
}

- (void)moveHandWithStartLabels:(NSMutableArray *)labelArray directions:(NSMutableArray *)directions {
    if ([directions count] == 0 || !_selectedLabel.hidden || _animationStopped) {
        [labelArray removeAllObjects];
        [directions removeAllObjects];
        return;
    }
    
    ArrowDirection direction = [[directions objectAtIndex:0] integerValue];
    [directions removeObjectAtIndex:0];
    
    UILabel *label = [labelArray objectAtIndex:0];
    [labelArray removeObjectAtIndex:0];
    
    _handImageView.alpha = 1;
    _handImageView.hidden = NO;
    _handImageView.top = label.frame.origin.y;
    _handImageView.left = label.frame.origin.x;
    if (ArrowDirectionLeft == direction) {
        _handImageView.top += nItemWidth / 2;
        _handImageView.left += _handImageView.image.size.width * 0.33;
    } else if (ArrowDirectionRight == direction) {
        _handImageView.top += nItemWidth / 2;
        _handImageView.right += _handImageView.image.size.width * 0.33;
    } else if (ArrowDirectionUp == direction) {
        _handImageView.top += nItemWidth / 2;
        _handImageView.left += _handImageView.image.size.width * 0.33;
    } else if (ArrowDirectionDown == direction) {
        _handImageView.top += nItemWidth / 2;
        _handImageView.left += _handImageView.image.size.width * 0.33;
    }
    
    _lineView.alpha = 0.6;
    _lineView.hidden = NO;
    _lineView.width = 6;
    _lineView.height = 6;
    _lineView.center = label.center;
    
    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        if (ArrowDirectionLeft == direction) {
            _handImageView.left -= nItemWidth + nSpaceWidth;
            [_lineView setFrame:CGRectMake(_lineView.left - (nItemWidth + nSpaceWidth), _lineView.top, nItemWidth + nSpaceWidth + 6, 6)];
        } else if (ArrowDirectionRight == direction) {
            _handImageView.right += nItemWidth + nSpaceWidth;
            _lineView.width = nItemWidth + nSpaceWidth + 6;
        } else if (ArrowDirectionUp == direction) {
            _handImageView.top -= nItemWidth + nSpaceWidth;
            [_lineView setFrame:CGRectMake(_lineView.left, _lineView.top - (nItemWidth + nSpaceWidth), 6, nItemWidth + nSpaceWidth + 6)];
        } else if (ArrowDirectionDown == direction) {
            _handImageView.bottom += nItemWidth + nSpaceWidth;
            _lineView.height = nItemWidth + nSpaceWidth + 6;
        }
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5 animations:^{
            _handImageView.alpha = 0;
            _lineView.alpha = 0;
        } completion:^(BOOL finished) {
            _handImageView.hidden = YES;
            _lineView.hidden = YES;
            [self moveHandWithStartLabels:labelArray directions:directions];
        }];
    }];
//    [UIView animateWithDuration:1 animations:^{
//        if (ArrowDirectionLeft == direction) {
//            _handImageView.left -= nItemWidth + nSpaceWidth;
//            [_lineView setFrame:CGRectMake(_lineView.left - (nItemWidth + nSpaceWidth), _lineView.top, nItemWidth + nSpaceWidth + 6, 6)];
//        } else if (ArrowDirectionRight == direction) {
//            _handImageView.right += nItemWidth + nSpaceWidth;
//            _lineView.width = nItemWidth + nSpaceWidth + 6;
//        } else if (ArrowDirectionUp == direction) {
//            _handImageView.top -= nItemWidth + nSpaceWidth;
//            [_lineView setFrame:CGRectMake(_lineView.left, _lineView.top - (nItemWidth + nSpaceWidth), 6, nItemWidth + nSpaceWidth + 6)];
//        } else if (ArrowDirectionDown == direction) {
//            _handImageView.bottom += nItemWidth + nSpaceWidth;
//            _lineView.height = nItemWidth + nSpaceWidth + 6;
//        }
//        
//        
//    } completion:^(BOOL finished) {
//        [UIView animateWithDuration:0.5 animations:^{
//            _handImageView.alpha = 0;
//            _lineView.alpha = 0;
//        } completion:^(BOOL finished) {
//            _handImageView.hidden = YES;
//            _lineView.hidden = YES;
//            [self moveHandWithStartLabels:labelArray directions:directions];
//        }];
//    }];
}

- (void)teachUserWithLevel:(NSInteger)level {
    NSMutableArray *labelArray = [[NSMutableArray alloc] init];
    NSMutableArray *directions = [[NSMutableArray alloc] init];
    if (level == 1) {
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionLeft]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionLeft]];
        UILabel *label = [_cellBtnArray objectAtIndex:17];
        [labelArray addObject:label];
        [labelArray addObject:label];
    } else if (level == 2) {
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionRight]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionDown]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionLeft]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionUp]];
        UILabel *label = [_cellBtnArray objectAtIndex:17];
        [labelArray addObject:label];
        [labelArray addObject:label];
        [labelArray addObject:label];
        [labelArray addObject:label];
    } else if (level == 3) {
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionRight]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionDown]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionLeft]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionUp]];
        UILabel *label = [_cellBtnArray objectAtIndex:22];
        [labelArray addObject:label];
        [labelArray addObject:label];
        [labelArray addObject:label];
        [labelArray addObject:label];
    } else if (level == 4) {
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionDown]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionDown]];
        UILabel *label = [_cellBtnArray objectAtIndex:17];
        [labelArray addObject:label];
        [labelArray addObject:label];
    } else if (level == 5) {
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionDown]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionDown]];
        UILabel *label = [_cellBtnArray objectAtIndex:12];
        [labelArray addObject:label];
        
        label = [_cellBtnArray objectAtIndex:17];
        [labelArray addObject:label];
    } else if (level == 6) {
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionRight]];
        [directions addObject:[NSNumber numberWithInt:ArrowDirectionLeft]];
        UILabel *label = [_cellBtnArray objectAtIndex:16];
        [labelArray addObject:label];
        
        label = [_cellBtnArray objectAtIndex:18];
        [labelArray addObject:label];
    }
    
    if ([labelArray count] > 0 && [directions count] > 0 && [labelArray count] == [directions count]) {
        _animationStopped = NO;
        [self moveHandWithStartLabels:labelArray directions:directions];
    }
}

- (void)resetFrameWithView:(UIImageView *)imageView {
    _handImageView.left += nItemWidth;
}

#pragma mark - 手势(touchEvent)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[touches allObjects] objectAtIndex:0];
    CGPoint point = [touch locationInView:_theView];

    UILabel *btn = [self getLabelWithPoint:point];
    
    if (btn && btn.text.length > 0 && [btn.text intValue]>0) {
        [_selectedLabel setText:btn.text];
        [_selectedLabel setHidden:NO];
        [_selectedLabel setCenter:btn.center];
        _differencePoint = CGPointMake(btn.center.x-point.x, btn.center.y-point.y);
        [_theView bringSubviewToFront:_selectedLabel];
        [btn setText:@""];
        [btn setBackgroundColor:[[SGEatNumber defaultEatNumber] getNumberColor:GameCellValue_Blank]];
        
        NSInteger fromIndex = [self getIndexWithPoint:point];
        [[SGEatNumber defaultEatNumber] setFromIndex:fromIndex];
        
        [UIView animateWithDuration:0.1 animations:^{
            [_selectedLabel setTransform:CGAffineTransformMakeScale(1.1, 1.1)];
        }];
    }
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (_selectedLabel.isHidden) {
        return;
    }
    
    UITouch *touch = [[touches allObjects] objectAtIndex:0];
    CGPoint point = [touch locationInView:_theView];
    
    CGPoint boxCenter = CGPointMake(point.x+_differencePoint.x, point.y+_differencePoint.y);
    [_selectedLabel setCenter:boxCenter];
    [self moveSelectLabelWithPoint:boxCenter isMoving:YES];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (_selectedLabel.isHidden) {
        return;
    }
    
    UITouch *touch = [[touches allObjects] objectAtIndex:0];
    CGPoint point = [touch locationInView:_theView];
    
    CGPoint boxCenter = CGPointMake(point.x+_differencePoint.x, point.y+_differencePoint.y);
    
    [self moveSelectLabelWithPoint:boxCenter isMoving:NO];
}

- (void)moveSelectLabelWithPoint:(CGPoint)point isMoving:(BOOL)isMoving {
    NSInteger index = [self getIndexWithPoint:point];
    if (_cellBtnArray.count <= index) {
        [self moveSelectedLabelToOldPos];
        return;
    }
    UILabel *tobtn = [_cellBtnArray objectAtIndex:index];

    if ([[SGEatNumber defaultEatNumber] cellCanMoveToIndex:index]) {
        NSLog(@"可以移动，从%ld->%ld, %@", (long)[[SGEatNumber defaultEatNumber] fromIndex], (long)index, isMoving ? @"移动中" : @"移动完毕");
        NSString *valueString = [NSString stringWithFormat:@"%ld", (long)[[SGEatNumber defaultEatNumber] mergeToIndex:index]];
        // 显示框高亮
        [_highLightedLabel setCenter:tobtn.center];
        [_highLightedLabel setHidden:NO];
        [SGAppDelegate playGameDefaultSoundWithState:self.isMusicOn];
        
        if (isMoving) {
            [[SGEatNumber defaultEatNumber] cellMoveToIndex:index isMoving:YES];
            [_selectedLabel setText:valueString];
            [[SGEatNumber defaultEatNumber] setFromIndex:index];
            if ([tobtn.text length] > 0) {
                [tobtn setText:@""];
                [tobtn setBackgroundColor:[[SGEatNumber defaultEatNumber] getNumberColor:GameCellValue_Blank]];
            }
        } else {
            [UIView animateWithDuration:0.1 animations:^{
                [_selectedLabel setTransform:CGAffineTransformMakeScale(1., 1.)];
                [_selectedLabel setFrame:CGRectMake(GET_COL_INDEX(index) * (nItemWidth + nSpaceWidth), GET_ROW_INDEX(index) * (nItemWidth + nSpaceWidth), nItemWidth, nItemWidth)];
            } completion:^(BOOL finished) {
                [_selectedLabel setHidden:YES];
                [_highLightedLabel setHidden:YES];
                [tobtn setText:valueString];
                [tobtn setBackgroundColor:[[SGEatNumber defaultEatNumber] getNumberColor:[valueString integerValue]]];
                
                [[SGEatNumber defaultEatNumber] cellMoveToIndex:index isMoving:NO];
            }];
        }
    } else if (!isMoving) { // 移动结束了，并且失败的情况
        [self moveSelectedLabelToOldPos];
    }
}

- (void)moveSelectedLabelToOldPos {
    UILabel *fbtn = [_cellBtnArray objectAtIndex:[[SGEatNumber defaultEatNumber] fromIndex]];
    [UIView animateWithDuration:0.1 animations:^{
        [_selectedLabel setTransform:CGAffineTransformMakeScale(1., 1.)];
        NSInteger x = GET_COL_INDEX([[SGEatNumber defaultEatNumber] fromIndex]);
        NSInteger y = GET_ROW_INDEX([[SGEatNumber defaultEatNumber] fromIndex]);
        [_selectedLabel setFrame:CGRectMake(x * (nItemWidth + nSpaceWidth),
                                            y * (nItemWidth + nSpaceWidth), nItemWidth, nItemWidth)];
    } completion:^(BOOL finished) {
        [_selectedLabel setHidden:YES];
        [fbtn setText:_selectedLabel.text];
        [fbtn setBackgroundColor:[[SGEatNumber defaultEatNumber] getNumberColor:[_selectedLabel.text integerValue]]];
        
        [[SGEatNumber defaultEatNumber] updateGameProgress];
    }];
    
    [_highLightedLabel setHidden:YES];
}

- (void)showGameFinishedViewWithGameProgress:(GameProgress)progress withAnimate:(BOOL)animate {
    if (!_gameFinishedView) {
        _gameFinishedView = [[SGGameFinishedView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _gameFinishedView.delegate = self;
    }
    
    if ([[SGEatNumber defaultEatNumber] getCurLevel] == 150) {
        progress = GameProgress_AllFinished;
    }
    
#ifdef DEBUG
    progress = GameProgress_AllFinished;
#endif
    [_gameFinishedView showInParentView:self.view progress:progress animate:animate];
}

#pragma makr - SGGameFinishedViewDelegate
- (void)goBack:(SGGameFinishedView *)gameFinishedView {
    [gameFinishedView removeFromSuperview];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)restart:(SGGameFinishedView *)gameFinishedView {
    [gameFinishedView removeFromSuperview];
    if ([gameFinishedView playerIsWin]) { // 玩家胜利了，开始下一关
        [[SGEatNumber defaultEatNumber] newGameWithNextLevel:YES];
    } else {
        [[SGEatNumber defaultEatNumber] newGameWithNextLevel:NO];
    }
    
    [self updateGameCellValue];
    [_titleLabel setText:[NSString stringWithFormat:@"LEVEL %d", (int)[[SGEatNumber defaultEatNumber] getCurLevel]]];
    
    NSInteger curLevel = [[SGEatNumber defaultEatNumber] getCurLevel];
    if (curLevel > 10) {
        [Appirater userDidSignificantEvent:YES];
    }
}

- (void)share:(SGGameFinishedView *)gameFinishedView {
//    if ([gameFinishedView playerIsWin]) {
//        NSArray *socialArray = @[UMShareToWechatSession, UMShareToWechatTimeline, UMShareToQQ, UMShareToQzone, UMShareToSina,
//                                 UMShareToRenren, UMShareToDouban, UMShareToSms];
//        [UMSocialConfig showNotInstallPlatforms:@[UMShareToWechatSession]];
//        [UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskLandscapeLeft];
//        
//        [UMSocialSnsService presentSnsIconSheetView:self
//                                          appKey:UMENG_APP_KEY
//                                       shareText:@"分享测试"
//                                      shareImage:nil
//                                 shareToSnsNames:socialArray
//                                        delegate:self];
//    }
}

- (void)restartGame {
    [[SGEatNumber defaultEatNumber] newGameWithNextLevel:NO];
    [self updateGameCellValue];
}

#pragma mark - SGEatNumberDelegate
- (void)updateGameProgress:(GameProgress)progress {
    if (progress == GameProgress_InPlaying) {
        NSLog(@"update value!!!");
    } else if (progress == GameProgress_PlayerFail) {
        NSLog(@"fail!!!");
        _animationStopped = YES;
        [self showGameFinishedViewWithGameProgress:GameProgress_PlayerFail withAnimate:YES];
    } else if (progress == GameProgress_PlayerWin) {
        NSLog(@"win!!!");
        _animationStopped = YES;
        [self showGameFinishedViewWithGameProgress:GameProgress_PlayerWin withAnimate:YES];
    }
}

#pragma mark - 参数转换

- (UILabel *)getLabelWithPoint:(CGPoint)point {
    if (point.x < nLeftSpace || point.x>SCREEN_WIDTH-nLeftSpace) {
        return nil;
    }
    CGPoint coord = [self getCoordWithPoint:point];
    return [self getLabelWithCoord:coord];
}

- (UILabel *)getLabelWithCoord:(CGPoint)coord {
    int index = coord.y*GAME_COL_MAX + coord.x;
    if (_cellBtnArray.count > index) {
        UILabel *btn = [_cellBtnArray objectAtIndex:index];
        return btn;
    }
    
    return nil;
}

- (NSInteger)getIndexWithPoint:(CGPoint)point {
    int col = point.x / (nSpaceWidth + nItemWidth);
    int row = point.y / (nSpaceWidth + nItemWidth);
    
    return GET_INDEX(row, col);
}

- (CGPoint)getCoordWithPoint:(CGPoint)point {
    int x = point.x / (nSpaceWidth + nItemWidth);
    int y = point.y / (nSpaceWidth + nItemWidth);
    
    return CGPointMake(x, y);
}

#pragma mark - UMSocailUIDelegate
//-(void)didSelectSocialPlatform:(NSString *)platformName withSocialData:(UMSocialData *)socialData {
//    NSLog(@"platformName:%@", platformName);
//    NSLog(@"socialData:%@", socialData);
//}

#pragma mark - UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    return NO;
}

@end
